
function extractIdFromUrl() {
    // 使用正则表达式匹配URL中的数字ID  
    // 假设ID是URL的最后一个部分，并且紧跟在"/explore/"之后  
    let url = window.location.href;
    const regex = /\/explore\/(\w+)/;
    const match = url.match(regex);

    // 如果找到了匹配项，则返回ID（即匹配项的第二部分）  
    if (match && match.length > 1) {
        return match[1];
    }

    // 如果没有找到匹配项，则返回null或空字符串  
    return null;
}
function drawVideoUrl(data) {
    let reg = new RegExp('masterUrl":"(.*?)"')
    return reg.exec(data)
}
function decodeVideoUrl(videoUrl) {
    while (videoUrl.indexOf("\\u002F") != -1) {
        videoUrl = videoUrl.replace("\\u002F", "/")
    }
    return videoUrl
}
function getType(url) {
    console.log(url);
    if (url.includes("jpeg")) {
        return ".jpg";
    } else if (url.includes("webp")) {
        return ".webp";
    } else if (url.includes("png")) {
        return ".png";
    } else {
        return ".jpg";
    }
}

//获取详情
const getDetail = () => document.querySelector('#detail-desc span').innerHTML;
//获取标题
const getTitle = () => document.querySelector("#detail-title") ? document.querySelector("#detail-title").innerText : null;
// 获取笔记标签
const getTags = () => {
    let tags = document.querySelectorAll('#hash-tag');
    if (!tags) {
        return ''
    } else {
        return document.querySelectorAll('#hash-tag').forEach(item => item.innerHTML)
    }
}

//获取点赞总数
const getlikesNum = () => document.querySelectorAll('.engage-bar .count')[0].innerHTML;

//获取收藏总数
const getCollectionNum = () => document.querySelectorAll('.engage-bar .count')[1].innerHTML;
//获取评论总数
const getCommentsNum = () => document.querySelectorAll('.engage-bar .count')[2].innerHTML;

//获取作者信息
const getUserInfo = () => {
    return {
        userName: document.querySelectorAll('.author-wrapper .username')[0].innerHTML,
    }
}
//获取图集/视频
const getImagesOrVideo = async () => {
    const swiperWrapperArr = Array.from(document.querySelectorAll(".swiper-wrapper div"))
    const urlArr = [];//url 数组
    const note = document.querySelector("div.note-content").innerText;
    if (swiperWrapperArr.length > 0) {
        //获取url并且对url进行去重操作
        const uniqueSwiperWrapperArr = swiperWrapperArr.map(item => item["style"]["backgroundImage"].replace(`url("`, "").replace(`")`, "")).filter((value, index, self) => {
            return self.indexOf(value) === index;
        })
        uniqueSwiperWrapperArr.forEach((url, index, array) => {
            urlArr.push({
                fileUrl: url,
                fileName: "[图文]" + note.substring(0, 10) + "-" + (index < 10 ? "0" + index : index) + getType(url),
            })
        })
    } else {
        const htmlBody = await fetch(document.URL, {
            headers: new Headers({
                "Cookie": document.cookie
            })
        })
        const videoData = await htmlBody.text();
        if (drawVideoUrl(videoData)) {
            const vData = drawVideoUrl(videoData)
            if (vData.length >= 2) {
                const videoUrl = decodeVideoUrl(vData[1])
                urlArr.push({
                    fileUrl: videoUrl,
                    fileName: "[视频]" + note.substring(0, 10) + ".mp4",
                })
                let cover = document.querySelector("#noteContainer xg-poster")["style"]["background-image"]
                if (cover) {
                    cover = cover.replace(`url("`, "").replace(`")`, "")
                    if (cover) {
                        urlArr.push({
                            fileUrl: cover,
                            fileName: "[封面]" + note.substring(0, 10) + getType(cover),
                        })
                    }
                }
            }
        }
    }
    console.log(urlArr, 'urlArr')
    return urlArr;
}

window.onload = async function () {

    //
    // tabId = null;
    // console.log(chrome, 'chrome.tabs')
    // chrome.tabs.getCurrent(function (tab) {
    //     var tabId = tab.id;
    //     console.log("当前标签页 ID：" + tabId);
    // });
    console.log(getImagesOrVideo(), 'getImagesOrVideo()')
    chrome.runtime.sendMessage(
        {
            greeting: "returnDetail",
            data: {
                id: extractIdFromUrl(),
                detail: getDetail(),
                title: getTitle(),
                files: await getImagesOrVideo(),
                likesNum: getlikesNum(),
                collectionNum: getCollectionNum(),
                commentsNum: getCommentsNum(),
                userInfo: getUserInfo()
            }
        },
        function (response) {
            window.close();
        }
    );
}
